package com.certification.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.certification.dto.ProfessionSelfEvaluationDTO;
import com.certification.entity.Certification;
import com.certification.entity.ProfessionSelfEvaluation;
import com.certification.mapper.ProfessionSelfEvaluationMapper;
import com.certification.service.CertificationService;
import com.certification.service.ProfessionSelfEvaluationService;
import com.certification.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;

import static com.certification.constants.CertConstant.CERTIFICATION;
import static com.certification.constants.CertConstant.PROFESSION_SELF_EVALUATION;
import static com.certification.constants.CertStatusConstant.CERTING;
import static com.certification.constants.CertStatusConstant.CERT_SUCCESS;


/**
 * @author copa
 * @createDate 2022-03-29 21:17
 * @function
 */
@Service
public class ProfessionSelfEvaluationServiceImpl implements ProfessionSelfEvaluationService {

    @Resource
    private ProfessionSelfEvaluationMapper professionSelfEvaluationMapper;

    @Resource
    private CertificationService certificationService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseMessage<String> addPro(ProfessionSelfEvaluationDTO professionSelfEvaluationDTO, Integer userId) {
        Certification cert = certificationService.getOneCertByCertStageAndPrincipalId(
                CERTIFICATION, userId, null, CERT_SUCCESS);
        if (Objects.isNull(cert)) {
            return ResponseMessage.errorMsg("请求错误~没有该数据~");
        }
        ProfessionSelfEvaluation professionSelfEvaluation = new ProfessionSelfEvaluation();
        BeanUtils.copyProperties(professionSelfEvaluationDTO, professionSelfEvaluation);
        professionSelfEvaluation.setCertId(cert.getId());
        int insert = professionSelfEvaluationMapper.insert(professionSelfEvaluation);
        if (insert < 1) {
            return ResponseMessage.errorMsg("系统繁忙~请稍后再试~");
        }
        cert.setCertStatus(CERTING)
                .setCertStage(PROFESSION_SELF_EVALUATION);
        if (certificationService.put(cert) < 1) {
            return ResponseMessage.errorMsg("系统繁忙~请稍后再试~");
        }
        return ResponseMessage.successMsg("新增指标成功~等待审核~");
    }

    @Override
    public ResponseMessage<List<ProfessionSelfEvaluationVO>> getPro(Integer userId) {
        List<ProfessionSelfEvaluationVO> professionSelfEvaluationVOList =
                professionSelfEvaluationMapper.selectProByUserId(userId);
        return ResponseMessage.success(professionSelfEvaluationVOList);
    }

    @Override
    public ResponseMessage<ProfessionSelfEvaluation> getProDetail(Integer proId, Integer userId) {
        ProfessionSelfEvaluation professionSelfEvaluation = professionSelfEvaluationMapper.selectById(proId);
        ResponseMessage<CertificationVO> certResponseMessage = certificationService.getCert(PROFESSION_SELF_EVALUATION, userId);
        if (certResponseMessage.isNotSuccess() || Objects.isNull(certResponseMessage.getData())) {
            return ResponseMessage.errorMsg(certResponseMessage.getMsg());
        }
        return ResponseMessage.success(professionSelfEvaluation);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseMessage<ProfessionSelfEvaluation> putPro(ProfessionSelfEvaluationDTO professionSelfEvaluationDTO, Integer userId) {
        Certification cert = certificationService.getOneCertByCertStageAndPrincipalId(
                PROFESSION_SELF_EVALUATION, userId, null, CERTING
        );
        if (Objects.isNull(cert)) {
            return ResponseMessage.errorMsg("该记录现阶段不能被修改~");
        }
        ProfessionSelfEvaluation evaluation = new ProfessionSelfEvaluation();
        BeanUtils.copyProperties(professionSelfEvaluationDTO, evaluation);
        evaluation.setCertId(cert.getId());
        int update = professionSelfEvaluationMapper.updateById(evaluation);
        if (update < 1) {
            return ResponseMessage.errorMsg("系统繁忙~请稍后再试~");
        }
        return ResponseMessage.successMsg("修改成功~等待审核~");
    }

    @Override
    public ResponseMessage<ProfessionSelfEvaluation> getProDetailAdmin(Integer certId) {
        Certification cert = certificationService.getOneCertByCertStageAndPrincipalId(
                PROFESSION_SELF_EVALUATION, null, certId, CERTING
        );
        if (Objects.isNull(cert)) {
            return ResponseMessage.errorMsg("没有查到该专业自评记录~");
        }
        LambdaQueryWrapper<ProfessionSelfEvaluation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(true, ProfessionSelfEvaluation::getCertId, certId);
        ProfessionSelfEvaluation professionSelfEvaluation = professionSelfEvaluationMapper.selectOne(wrapper);
        if (Objects.isNull(professionSelfEvaluation)) {
            return ResponseMessage.errorMsg("没有查到该专业自评记录~");
        }
        return ResponseMessage.success(professionSelfEvaluation);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseMessage<String> putProAdmin(Integer certId, Integer status, String remark) {
        ResponseMessage<ProfessionSelfEvaluation> proResponseMessage = getProDetailAdmin(certId);
        if (proResponseMessage.isNotSuccess()) {
            return ResponseMessage.errorMsg(proResponseMessage.getMsg());
        }
//        ProfessionSelfEvaluation pro = proR.getData();

        ResponseMessage<String> res = certificationService.putCertAdmin(certId, status, remark, PROFESSION_SELF_EVALUATION);
        if (res.isNotSuccess()) {
            return ResponseMessage.errorMsg(res.getMsg());
        }
        return ResponseMessage.successMsg("操作成功~");
    }

    @Override
    public ResponseMessage<String> postExpertAdvice(Integer certId, Integer status, String expertAdvice) {
        ResponseMessage<ProfessionSelfEvaluation> proResponseMessage = getProDetailAdmin(certId);
        if (proResponseMessage.isNotSuccess()) {
            return ResponseMessage.errorMsg(proResponseMessage.getMsg());
        }
        ProfessionSelfEvaluation pro = proResponseMessage.getData();
        if (pro.getExpertAdviceStatus() > 0) {
            return ResponseMessage.errorMsg("该专业自评记录已经提出意见了");
        }
        pro.setExpertAdviceStatus(status)
                .setExpertAdvice(pro.getExpertAdviceStatus() == 2 ? expertAdvice : null);
        int update = professionSelfEvaluationMapper.updateById(pro);
        if (update < 1) {
            return ResponseMessage.errorMsg("系统繁忙~请稍后再试~");
        }
        return ResponseMessage.successMsg("操作成功");
    }

    @Override
    public ResponseMessage<String> putExpertAdvice(Integer certId, String expertAdvice) {
        ResponseMessage<ProfessionSelfEvaluation> proResponseMessage = getProDetailAdmin(certId);
        if (proResponseMessage.isNotSuccess()) {
            return ResponseMessage.errorMsg(proResponseMessage.getMsg());
        }
        ProfessionSelfEvaluation pro = proResponseMessage.getData();
        if (1 == pro.getExpertAdviceStatus()) {
            return ResponseMessage.errorMsg("该记录已经提出肯定建议~不可撤回~");
        }
        pro.setExpertAdvice(expertAdvice);
        int update = professionSelfEvaluationMapper.updateById(pro);
        if (update < 1) {
            return ResponseMessage.errorMsg("系统繁忙~请稍后再试~");
        }
        return ResponseMessage.successMsg("操作成功");
    }

    @Override
    public ResponseMessage<ProfessionSelfEvaluation> getProDetailByCertId(Integer certId) {
        Map<String, Object> selectMap = new HashMap<>();
        selectMap.put("cert_id", certId);
        List<ProfessionSelfEvaluation> list = professionSelfEvaluationMapper.selectByMap(selectMap);
        if (Objects.isNull(list) || list.isEmpty()) {
            return ResponseMessage.errorMsg("没有查到该记录~");
        }
        return ResponseMessage.success(list.get(0));
    }

    @Override
    public ResponseMessage<IPage<ProfessionSelfEvaluationVO>> getProPage(Integer userId, FindCertVO findProVO) {
        IPage<ProfessionSelfEvaluationVO> professionSelfEvaluationVOList =
                professionSelfEvaluationMapper.selectProByUserIdPage(userId, findProVO.getCertId() ,new Page<>(findProVO.getPageNum(), findProVO.getPageSize()));
        return ResponseMessage.success(professionSelfEvaluationVOList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseMessage<String> addProList(List<ProfessionSelfEvaluationDTO> professionSelfEvaluationDTOList, Integer userId) {
        Certification cert = certificationService.getOneCertByCertStageAndPrincipalId(
                CERTIFICATION, userId, null, CERT_SUCCESS);
        if (Objects.isNull(cert)) {
            return ResponseMessage.errorMsg("请求错误~没有该数据~");
        }
        AtomicBoolean flag = new AtomicBoolean(true);
        professionSelfEvaluationDTOList.forEach(professionSelfEvaluationDTO -> {
            ProfessionSelfEvaluation professionSelfEvaluation = new ProfessionSelfEvaluation();
            BeanUtils.copyProperties(professionSelfEvaluationDTO, professionSelfEvaluation);
            professionSelfEvaluation.setCertId(cert.getId());
            int insert = professionSelfEvaluationMapper.insert(professionSelfEvaluation);
            if (insert < 1) {
                flag.set(false);
            }
        });
        if (!flag.get()) {
            return ResponseMessage.errorMsg("系统繁忙~请稍后再试~");
        }
        cert.setCertStatus(CERTING)
                .setCertStage(PROFESSION_SELF_EVALUATION);
        if (certificationService.put(cert) < 1) {
            return ResponseMessage.errorMsg("系统繁忙~请稍后再试~");
        }
        return ResponseMessage.successMsg("新增指标成功~等待审核~");
    }

    @Override
    public Long countImprove(Integer certId) {
        LambdaQueryWrapper<ProfessionSelfEvaluation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(true, ProfessionSelfEvaluation::getCertId, certId);
        wrapper.eq(true, ProfessionSelfEvaluation::getCorrectStatus, 0);
        return professionSelfEvaluationMapper.selectCount(wrapper);
    }

    @Override
    public ProfessionSelfEvaluation getProByIdAndCertId(Integer proId, Integer certId) {
        LambdaQueryWrapper<ProfessionSelfEvaluation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(true, ProfessionSelfEvaluation::getCertId, certId);
        wrapper.eq(true, ProfessionSelfEvaluation::getId, proId);
        return professionSelfEvaluationMapper.selectOne(wrapper);
    }

    @Override
    public Integer putPro(ProfessionSelfEvaluation professionSelfEvaluation) {
        return professionSelfEvaluationMapper.updateById(professionSelfEvaluation);
    }
}
